package com.test.fundible.fundible_03_login;

import static com.test.fundible.fundible_00_utils.FundibleUtil.startLoading;
import static com.test.fundible.fundible_00_utils.FundibleUtil.stopLoading;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.test.fundible.R;
import com.test.fundible.fundible_00_analytics.fundibleevent.FundibleIAnalyticsEvent;
import com.test.fundible.fundible_00_analytics.FundibleUtil.FundibleAnalyticsUtil;
import com.test.fundible.fundible_00_customer_service.Customer_fundibleServiceDialog;
import com.test.fundible.fundible_00_http.OkHttpUtil;
import com.test.fundible.fundible_00_utils.FundibleConfigs;
import com.test.fundible.fundible_00_utils.FundibleUtil;
import com.test.fundible.fundible_00_utils.Kind_fundibleTip_fundibleDialog;
import com.test.fundible.fundible_01_launcher.App_fundibleShow_fundibleCustomize;
import com.test.fundible.fundible_04_home.MainAct_fundibleivity;

import org.json.JSONException;
import org.json.JSONObject;

public class Login_fundibleViaC_fundibleallActivity extends AppCompatActivity {

    private final TextView[] codeTvs = new TextView[4];
    private View codeErrorTipsView;
    private TextView codeErrorTipsTv;
    private Button loginBtn;
    private ImageButton ppCheckIb;
    private TextView ppTv;
    private final View[] numBtns = new View[10];
    private View numDelBtn;

    private int inputPosit = 0;
    private boolean isPPAgree = true;
    private String mobile = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fundible_login_fundible_via_call);
        //tag2024
//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);

        mobile = getIntent().getStringExtra("mobile");
        if (TextUtils.isEmpty(mobile)){
            OkHttpUtil.getInstance_fundible().uploadEventPoint("LOGIN_VIA_CALL","ERROR_MOBILE_IS_NULL","");
            return;
        }

        isPPAgree = getIntent().getBooleanExtra("isPPAgree",true);

        findViewById(R.id.aflfvc_ib_back).setOnClickListener(v -> onBackPressed());
        findViewById(R.id.aflfvc_ib_customerservice).setOnClickListener(v -> {
            OkHttpUtil.getInstance_fundible().uploadEventPoint("LOGIN_VIA_CALL","CUSTOMER_SERVICE_CLICK","");
            new Customer_fundibleServiceDialog(this).show();
        });

        codeTvs[0] = findViewById(R.id.aflfvc_tv_code_0);
        codeTvs[1] = findViewById(R.id.aflfvc_tv_code_1);
        codeTvs[2] = findViewById(R.id.aflfvc_tv_code_2);
        codeTvs[3] = findViewById(R.id.aflfvc_tv_code_3);

        codeErrorTipsView = findViewById(R.id.aflfvc_view_code_error_tips);
        codeErrorTipsTv = findViewById(R.id.aflfvc_tv_code_error_tips);
        loginBtn = findViewById(R.id.aflfvc_btn_login);

        ppCheckIb = findViewById(R.id.aflfvc_ib_pp_check);
        ppTv = findViewById(R.id.aflfvc_tv_pp);

        numBtns[0] = findViewById(R.id.aflfvc_btn_num_0);
        numBtns[1] = findViewById(R.id.aflfvc_btn_num_1);
        numBtns[2] = findViewById(R.id.aflfvc_btn_num_2);
        numBtns[3] = findViewById(R.id.aflfvc_btn_num_3);
        numBtns[4] = findViewById(R.id.aflfvc_btn_num_4);
        numBtns[5] = findViewById(R.id.aflfvc_btn_num_5);
        numBtns[6] = findViewById(R.id.aflfvc_btn_num_6);
        numBtns[7] = findViewById(R.id.aflfvc_btn_num_7);
        numBtns[8] = findViewById(R.id.aflfvc_btn_num_8);
        numBtns[9] = findViewById(R.id.aflfvc_btn_num_9);

        numDelBtn = findViewById(R.id.aflfvc_btn_num_del);

        setPPState(isPPAgree);

        init();
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        OkHttpUtil.getInstance_fundible().uploadEventPoint("LOGIN_VIA_CALL","START","");
    }

    @Override
    protected void onPause() {
        super.onPause();
        OkHttpUtil.getInstance_fundible().uploadEventPoint("LOGIN_VIA_CALL","END","");
    }

    private void init(){

        ppTv.setOnClickListener(v -> {
            OkHttpUtil.getInstance_fundible().uploadEventPoint("LOGIN_VIA_CALL","STATEMENT_CLICK","");
            String agreementUrl = App_fundibleShow_fundibleCustomize.getInstance_fundible().getAgreementUrl_fundible();
            if (TextUtils.isEmpty(agreementUrl)) return;
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(agreementUrl)));
        });

        for (int i=0;i<numBtns.length;i++){
            final  int fI = i;
            View numBtn = numBtns[i];
            numBtn.setOnClickListener(v -> input(fI));
        }

        numDelBtn.setOnClickListener(v -> delete());

        for (TextView codTv:codeTvs){
            codTv.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {}
                @Override
                public void afterTextChanged(Editable s) {
                    String verCode = getCode();
                    if (TextUtils.isEmpty(verCode) || verCode.length()<4) loginBtn.setBackgroundResource(R.drawable.bg_gray_rc16dp);
                    else loginBtn.setBackgroundResource(R.drawable.bg_green_rc16dp);
                }
            });
        }

        loginBtn.setOnClickListener(v -> {
            String verCode = getCode();
            OkHttpUtil.getInstance_fundible().uploadEventPoint("LOGIN_VIA_CALL","LOGIN_CLICK",verCode);
            login(verCode);
        });

    }

    //输入
    private void input(int input) {

        inputPosit = Math.max(inputPosit,0);

        if (inputPosit<codeTvs.length) codeTvs[inputPosit].setText(String.valueOf(input));

        //下一个
        inputPosit++;

        //输入完成时自动登录
        if (inputPosit>3){
            inputPosit = 3;
            String vercode = getCode();
            OkHttpUtil.getInstance_fundible().uploadEventPoint("LOGIN_VIA_CALL","OTP_DONE",vercode);
            login(vercode);
        }

        //更新输入位置
        updateInputPosit();

    }

    //删除/回退
    private void delete(){

        inputPosit = Math.min(inputPosit,3);

        codeTvs[inputPosit].setText("");

        inputPosit--;

        inputPosit = Math.max(inputPosit,0);

        updateInputPosit();

    }

    //登陆
    private void login(String vercode){

        if (!isPPAgree){
            new Kind_fundibleTip_fundibleDialog(
                    this,
                    getString(R.string.kind_tips_login_desc),
                    getString(R.string.kind_tips_login_btn),
                    () -> setPPState(true)
            ).show();
            return;
        }

        if (TextUtils.isEmpty(vercode) || vercode.length()<4){
            Toast.makeText(this,getString(R.string.tips_enter_vercode_fundible),Toast.LENGTH_SHORT).show();
            return;
        }

        //测试账号自动登录
        if (App_fundibleShow_fundibleCustomize.getInstance_fundible().isTestAccount_fundible(mobile)){
            try {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("token", App_fundibleShow_fundibleCustomize.getInstance_fundible().getTestToken_fundible(mobile));
                jsonObject.put("userId", mobile);
                jsonObject.put("type", FundibleConfigs.LOGIN_TYPE_OL_fundibleD);
                jsonObject.put("isAdSource","NO");
                Log_fundibleinInfo.par_fundiblese(jsonObject);
                onLoginSuccessResponse();
            }catch (JSONException e){
                e.printStackTrace();
            }
            return;
        }

        startLoading(this,"");
        OkHttpUtil.getInstance_fundible().usLgWithCode(mobile, vercode, this::onLoginSuccessResponse, (code, msg) -> {
            //登录失败响应
            if (!TextUtils.isEmpty(msg)) codeErrorTipsTv.setText(msg);
            codeErrorTipsView.setVisibility(View.VISIBLE);
            for (TextView codeTv:codeTvs){
                codeTv.setBackgroundResource(R.drawable.bg_ver_code_red);
                codeTv.setTextColor(Color.WHITE);
            }
        });

    }

    //提取输入的验证码
    private String getCode(){
        StringBuilder result = new StringBuilder();
        for (TextView codeTv:codeTvs){
            result.append(codeTv.getText().toString());
        }
        return result.toString();
    }

    //协议勾选状态
    private void setPPState(boolean isPPAgree) {
        this.isPPAgree = isPPAgree;
        ppCheckIb.setBackgroundResource(isPPAgree ? R.drawable.icon_check_true :R.drawable.icon_check_false);
    }

    //登录成功响应
    public void onLoginSuccessResponse(){

        FundibleUtil.setMobile_fundible(mobile);
        FundibleUtil.setToken_fundible(Log_fundibleinInfo.getIns_fundibletance().getT_fundibleoken());
        FundibleUtil.setUserId_fundible(Log_fundibleinInfo.getIns_fundibletance().getUse_fundiblerId());
        FundibleUtil.setIsAdSource_fundible(Log_fundibleinInfo.getIns_fundibletance().getIs_fundibleAdSource());

        if (Log_fundibleinInfo.getIns_fundibletance().getT_fundibleype().equalsIgnoreCase(FundibleConfigs.LOGIN_T_fundibleYPE_REGISTER))
            FundibleAnalyticsUtil.INSTANCE.addEvent_fundible(FundibleIAnalyticsEvent.AT_REGISTER);

        FundibleAnalyticsUtil.INSTANCE.saveFirebaseAndFacebookS2SInfo_fundible();

        OkHttpUtil.getInstance_fundible().requestUsPrcs(this::onUserProcessResponse);

    }

    //用户流程响应
    public void onUserProcessResponse(){
        stopLoading();
        Intent intent = new Intent(this, MainAct_fundibleivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(intent);
        finish();
    }

    //输入位置显示
    private void updateInputPosit(){
        for (int i=0;i<codeTvs.length;i++){
            TextView codeTv = codeTvs[i];
            if (inputPosit == i){
                codeTv.setBackgroundResource(R.drawable.bg_ver_code_light);
                codeTv.setTextColor(getColor(R.color.green_light));
            }else {
                codeTv.setBackgroundResource(R.drawable.bg_ver_code_gray);
                codeTv.setTextColor(getColor(R.color.black));
            }
        }
    }


}